Skip to content

Cassette plugin#239

Closed
GrandMoff100 wants to merge 34 commits into
devfrom
cassette-plugin
Closed

Cassette plugin#239
GrandMoff100 wants to merge 34 commits into
devfrom
cassette-plugin

Conversation

@GrandMoff100
Copy link
Copy Markdown
Collaborator

No description provided.

adamlogan73 and others added 30 commits April 2, 2026 21:57
Swap type checker from mypy to zuban across CI, pre-commit, and
pyproject.toml. Relax pinned versions on docs, styling, and testing
dependency groups to use range constraints. Bump requires-python
to >=3.10 and websockets to >=16.
Remove the unified Client/WebsocketClient classes that combined sync and
async via use_async flag. Promote the Raw* implementations to be the
public API: Client, AsyncClient, WebsocketClient, AsyncWebsocketClient.
Drop the async_ prefix from async client methods since they now live on
separate classes. Move URL scheme validation into base classes.
Introduce Base*/Async* model variants for Domain, Entity, Group, Service,
and Event. Replace _client constructor pattern with explicit client field.
Bump minimum Python to 3.11, expand ruff rules to ALL, modernize type
annotations, and enforce single-line imports.
Replace the decorator-based processor registry with dict-based MIME
dispatch and separate sync/async entry points. Response content is now
read lazily only when needed for error messages, eliminating the
internal _buffer access hack. Remove custom processor registration
API and decode_bytes parameter.
- Rename get_domain() param from `domain` to `domain_id` on WS clients
- Change WS get_domain() return type to Domain | None using .get()
- Fix fire_event() return type on sync Client from str | None to str
- Add keyword-only marker for significant_changes_only in sync get_entity_histories()
- Remove redundant entity_id param from WS trigger_service methods
- Fix TemplateEvent.result type from str to Any (HA returns native types)
- Add str() conversion in WS get_rendered_template to match return annotation
- Document WS trigger_service return type differences (protocol limitation)
New models for entity registry responses (EntityRegistryEntry,
EntityRegistryEntryExtended, EntityRegistryUpdateResult) and
list/get/update/remove methods on both sync and async WS clients.
Also adds configurable max_size param to WS client init (default 16MB)
to handle large responses like full entity registry lists.

Update CI Python version from 3.9 to 3.11.
- Rewrite usage.rst async section: replace use_async=True/async_ prefix
  pattern with separate AsyncClient and AsyncWebsocketClient classes
- Fix advanced.rst: update caching params (cache_session -> session),
  remove obsolete "disabling caching" section, add use_cache docs
- Fix README.md: update async example to use AsyncClient, remove
  "async not supported" note for WebSocket
- Standardize docstrings across all four client classes: consistent
  voice, correct class references (Entity->AsyncEntity etc.), fix
  "homeassistant" -> "Home Assistant" naming
- Fix minor issues: typos, Python version (3.9->3.11), zuban in
  CONTRIBUTING.rst tooling list
- Fix broken f-string/%-style log format in sync client
- Align empty-params guard between sync and async clients
- Replace deprecated verify_ssl with ssl param in TCPConnector
- Stop prepare_headers from mutating caller's dict; allow header overrides
- Use ResponseError instead of mismatched RequestError in WebSocket layer
- Fix auth failure path that could raise unhandled ValidationError
- Make sync _subscribe_events use recv_result to match async
- Make include_id keyword-only in async send() to match sync
- Gracefully handle __exit__ when connection is already closed
- Clean up _event_responses in finally block during unsubscribe
- Suppress auth token from debug logging
- Validate History states are non-empty and share same entity_id
- Replace asyncio.Task and Container with deserializable types in models
- Add model_rebuild for ServiceFieldSelector circular reference
- Export all config entry and entity registry models from top-level package
- Fix async websocket fixture decorator in conftest
- Fix sync test_listen_config_entries to use explicit break like async version
- Strengthen test assertions and add cleanup safety in disable/enable tests
- Use tmp_path for SQLite cache in async session test
- Raise ReceivingError in __exit__/__aexit__ when connection is not open
- Remove duplicate check_success from handle_recv (parse_response already handles errors)
- Catch non-ValidationError exceptions in authentication_phase
- Add ResponseError to Service.trigger() fallback so it works for websocket clients
- Fix tests to expect ResponseError for websocket error responses
Replace all HTTP and WebSocket dependencies with niquests:
- requests + requests-cache -> niquests (sync REST client)
- aiohttp + aiohttp-client-cache -> niquests AsyncSession (async REST client)
- websockets -> niquests[ws] WebSocket extension (sync + async WS clients)

Drop built-in request caching support (requests-cache, aiohttp-client-cache).
Users can configure caching on their own session instances if needed.

WebSocket clients now use niquests' response extension API
(Session.get(ws://) -> response.extension.send_payload/next_payload).
Add fragment buffering in _recv to work around upstream urllib3-future
bug where next_payload() returns incomplete messages for large payloads.

Accept optional session parameter in WebSocket client constructors for
consistency with REST clients. Use non-nullable session types with del
for _ws in __exit__/__aexit__.
2.19.902 reverses header merge order so user headers overwrite extension
headers, breaking the WebSocket upgrade handshake (server sees a plain
GET and returns 400). Tracked upstream at jawah/urllib3.future#338.

Also accept http:// and https:// schemes in BaseWebsocketClient,
normalising to ws:// and wss:// internally.
…[tool.zuban] with default mode, and fix test type narrowing
…ches, and self-contained entity registry remove tests
Introduces a uv workspace package (packages/pytest-niquests-cassettes)
that intercepts niquests.Session.send and AsyncSession.send to record and
replay HTTP and WebSocket interactions. Cassettes are stored in
cassettes/session.yaml and replayed in CI without a running HA instance.

- Plugin provides --record, --cassette-dir, --cassette-file, and
  --cassette-match-on CLI options (default matchers: method + path)
- WebSocket frames are captured via RecordingExtension / AsyncRecordingExtension
  wrappers and replayed via FakeExtension / AsyncFakeExtension
- Test env vars made optional with sensible defaults for replay mode
- pytest_sessionstart server-readiness check skipped unless --record is passed
- Fixed timestamps in logbook/history tests to support query-string matching
…chers, serializers

- Rename package pytest-niquests-cassettes → nimax
- Add RecordMode enum (NONE, ONCE, NEW_EPISODES, ALL) replacing record: bool
- Add BaseMatcher ABC with 8 built-in matchers (method, uri, host, path, query, headers, body, protocol)
- Add BaseSerializer ABC with JSONSerializer and YAMLSerializer; auto-detect from file extension
- Add Placeholder dataclass for cassette sanitization
- Add Frame dataclass with type, offset_ms, close_code, close_reason; WebSocketSession with claim/cursor tracking
- Add NimaxRecorder programmatic API with use_cassette() context manager and register_matcher/register_serializer
- Switch from session-scoped autouse cassette to per-test nimax_session / nimax_async_session fixtures
- Auto-migrate legacy YAML cassette format (flat status/body/url keys) on load
- Add pyproject.toml config support via [tool.nimax]
- Add nimax-design.md and nimax-implementation-plan.md design documents
- Re-record all cassettes as per-test JSON files under cassettes/{module}/{test}.json
- Update conftest.py and test_client.py to use new fixture API
…jects/nimax

Switch uv source from workspace member to editable path dependency.
- Remove local path override for nimax, now resolved from PyPI (nimax==1.0.0)
- Move cassettes from cassettes/ to tests/cassettes/ and add [tool.nimax] config
- Switch cassette matcher from default path-only to method+uri to correctly
  distinguish ?return_response requests from plain service calls
- Fix EntityRegistryEntryExtended.aliases to tolerate None values from HA
- Update compose.yml image to ghcr.io prefix for podman compatibility
Tests no longer need a live HA instance — cassettes handle all HTTP
interactions. Removes the HA server container, Dockerfile build, entrypoint
wait, volume mounts, and hardcoded token from CI.
Tests were making raw connections to localhost:8123 which fails in CI
without a live HA instance. Thread nimax_session/nimax_async_session
through all four unauthorized tests so requests are cassette-backed.
@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 26, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.74%. Comparing base (fbefe2e) to head (f3fb58e).
⚠️ Report is 2 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #239      +/-   ##
==========================================
+ Coverage   99.66%   99.74%   +0.08%     
==========================================
  Files          29       29              
  Lines        2359     2776     +417     
==========================================
+ Hits         2351     2769     +418     
+ Misses          8        7       -1     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@adamlogan73 adamlogan73 deleted the cassette-plugin branch April 26, 2026 23:17
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants